import { requestAi, fileRequest } from "@/api/axios";
import type { AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "axios";
type RequestInstance = typeof requestAi | typeof fileRequest;

class RequestCacheController {
    private pendingRequests: Set<string> = new Set();

    public addRequest(url: string): void {
        this.pendingRequests.add(url);
    }

    public removeRequest(url: string): void {
        this.pendingRequests.delete(url);
    }

    public isRequestPending(url: string): boolean {
        return this.pendingRequests.has(url);
    }
     public removeAllRequests(): void {
        this.pendingRequests.clear();
    }
}

function createRequestWrapper(
    requestInstance: RequestInstance,
    cacheController: RequestCacheController
) {
    return async function makeRequest<T>(
        config: AxiosRequestConfig,
        requestInterceptor?: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig | Promise<InternalAxiosRequestConfig>,
        responseInterceptor?: (response: AxiosResponse<T>) => AxiosResponse<T> | Promise<AxiosResponse<T>>
    ): Promise<AxiosResponse<T>> {
        const url = config.url;
        if (!url) {
            return Promise.reject({ msg: "URL is required" });
        }

        let requestInterceptorId: number | null = null;
        let responseInterceptorId: number | null = null;
        // 动态挂载请求拦截器
        if (requestInterceptor) {
            requestInterceptorId = requestInstance.interceptors.request.use(requestInterceptor);
        }
        // 动态挂载响应拦截器
        if (responseInterceptor) {
            responseInterceptorId = requestInstance.interceptors.response.use(responseInterceptor);
        }

        // 检查是否有待处理的请求
        if (cacheController.isRequestPending(url)) {
            // 移除动态拦截器
            if (requestInterceptorId !== null) requestInstance.interceptors.request.eject(requestInterceptorId);
            if (responseInterceptorId !== null) requestInstance.interceptors.response.eject(responseInterceptorId);
            return Promise.resolve({
                data: null,
                msg: "Request is already pending(this error is  from local application)",
                code: 999,
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
            } as any);
        }

        try {
            cacheController.addRequest(url);
            const response = await requestInstance(config);
            return response;
        } catch (error) {
            console.error("Request failed:", error);
            throw error;
        } finally {
            cacheController.removeRequest(url);
            // 移除动态拦截器
            if (requestInterceptorId !== null) requestInstance.interceptors.request.eject(requestInterceptorId);
            if (responseInterceptorId !== null) requestInstance.interceptors.response.eject(responseInterceptorId);
        }
    };
}

const standardCacheController = new RequestCacheController();
const fileCacheController = new RequestCacheController();

const standardRequestAi = createRequestWrapper(requestAi, standardCacheController);
const fRequest = createRequestWrapper(fileRequest, fileCacheController);

export {
    requestAi,
    // 普通的一次性请求（在完成前不能重复发送）
    standardRequestAi,
    // 文件请求（带永久缓存，一旦请求过就不再重复请求）
    fRequest,
    // 导出 cacheController 以便外部移除 pending
    standardCacheController,
    fileCacheController,
};